package cn.learn.server;

import cn.learn.server.persistence.FileTxnSnapLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ZooKeeperServerMain {
    private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperServerMain.class);
    ServerCnxnFactory cnxnFactory;

    public static void main(String[] args) {
        ZooKeeperServerMain main = new ZooKeeperServerMain();
        try{
            main.initializeAndRun(args);
            System.in.read();
            System.out.println("输入退出！");
        }catch (Exception e) {

        }
    }

    protected void initializeAndRun(String[] args) throws Exception {
        // 这里都干些什么呢
        // 新建一个config,用来加载所有配置项
        ServerConfig config = new ServerConfig();
        config.parse(""); // 将配置文件中的配置参数加载到实体中
        // 开始运行
        runFromConfig(config);
    }

    public void runFromConfig(ServerConfig config) throws Exception {
        FileTxnSnapLog txnLog = new FileTxnSnapLog(config.dataLogDir, config.dataDir);

        ZooKeeperServer zkServer = new ZooKeeperServer(txnLog);

        if (config.getClientPortAddress() != null) {
            cnxnFactory = ServerCnxnFactory.createFactory(); // 创建NIOServerCnxnFactory
            cnxnFactory.configure(config.getClientPortAddress());
            cnxnFactory.startup(zkServer); // 启动
        }
    }
}
